<template>
  <!-- 
    搜索页面处理：
    1、静态页面结构 ：历史记录 + 搜索结果列表
    2.输入框 输入关键字 进行搜索
    3.axios 搜索文章 请求 获取数据 
    4.历史记录 显示之前已经获取过的文章
   -->
  <div class="search">
    <div class="header">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search
        v-model="userKey"
        placeholder="请输入搜索关键词"
        shape="round"
        autofocus="true"
      />
      <div @click="onSearch">搜索</div>
    </div>
    <div class="historyList">
      <h2>历史记录</h2>
      <span v-for="(v, i) in historyList" :key="i" @click="onSearch($event, v)">
        {{ v }}
      </span>
    </div>
    <div class="searchList">
      <h2>搜索结果</h2>
      <router-link
        :to="`/articleDetail/${value.id}`"
        v-for="(value, index) in searchList"
        :key="index"
        >{{ value.title }}</router-link
      >
    </div>
  </div>
</template>

<script>
import { post_search } from "@/api/article";
export default {
  data() {
    return {
      userKey: "", //用户搜索关键字
      searchList: [], //搜索结果列表
      historyList: [], //历史记录列表
    };
  },
  methods: {
    async onSearch(e, value) {
      if (value) {
        this.userKey = value;
      }
      let res = await post_search(this.userKey);
      console.log(res);
      this.searchList = res.data.data;
      //   console.log(this.searchList);

      //   判断数组中是否已有当前关键字
      let index = this.historyList.indexOf(this.userKey);
      if (index !== -1) {
        //   如果有则删除掉
        this.historyList.splice(index, 1);
      }
      if (this.historyList.length == 5) {
        this.historyList.pop();
      }
      this.historyList.unshift(this.userKey);
      localStorage.setItem("historyList", JSON.stringify(this.historyList));
    },
  },
  mounted() {
    this.historyList = JSON.parse(localStorage.getItem("historyList")) || [];
  },
};
</script>

<style lang='less' scoped>
.header {
  display: flex;
  height: 50px;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  border-bottom: 1px solid #ccc;
  .van-search {
    flex: 1;
    padding: 5px 12px;
  }
}
.historyList,
.searchList {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  h2 {
    line-height: 40px;
    font-weight: bold;
  }
  > a {
    display: block;
    text-decoration: underline;
    line-height: 30px;
    color: #666;
    // 添加样式让文本一行显示，超出的部分使用...替换
    word-break: keep-all;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  p {
    line-height: 30px;
    border-bottom: 1px dashed orange;
  }
}
</style>